<?php


namespace app\api\controller\v38;


use app\api\controller\v2\Auth;
use app\common\cachemodel\zl5\Zl5ExplainTitle;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\astrolog\Astrolog;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\AstroSettingUser1751;
use app\common\model\Recode;
use think\Env;
use think\Log;
use think\response\Json;

/**
 * @version 2.9.8
 * 星盘 2.9.8
 * Class Astrolabe
 * @package app\api\controller\v38
 */
class Astrolabe extends Auth
{
    /**
     * 查看星盘
     * @param string    chart   需要请求的星盘
     * @param int       tid     星盘类型 [1-3] 现代 古典 特殊
     * @return Json
     * @throws ApiException
     * @throws \Exception
     */
    public function index()
    {
        if (!$this->request->isGet())
        {
            return show(config('code.error'), '未知操作');
        }

        $param = $this->request->param();

        $check = $this->checkParam($param);

        if ($check !== true)
        {
            return show(config('code.error'), $check);
        }
        $param['chart'] = (string)$param['chart'];

        if ($param['chart'] !== 'now' && (empty($param['id']) && empty($param['id1']) && empty($param['id2'])))
        {
            return show(406, '档案缺失');
        }

        $param['tid'] = (int)$param['tid'];
        // 星盘配置方案使用默认值
        $tid = 1;

        (isset($param['tid']) && in_array($param['tid'], [1, 2, 3], true)) && $tid = $param['tid'];

        $settingData = (new AstroSettingUser1751())->getUserSettingByTid([
            'uid' => $this->user['id'],
            'tid' => $tid,
            'chart' => $param['chart'],
        ]);

        $Recode = new Recode();

        $Astrolog = Astrolog::getInstance();

        if (isset($param['id']) && $param['id'])
        {
            $Astrolog->setRecode1($Recode->getRecode(['id' => $param['id'], 'uid' => $this->user['id']]));
        }

        if (isset($param['id1']) && $param['id1'])
        {
            $Astrolog->setRecode1($Recode->getRecode(['id' => $param['id1'], 'uid' => $this->user['id']]));
        }

        if (isset($param['id2']) && $param['id2'])
        {
            $Astrolog->setRecode2($Recode->getRecode(['id' => $param['id2'], 'uid' => $this->user['id']]));
        }

        if (isset($param['datetime']) && $param['datetime'] !== '')
        {
            $advanceTime = strtotime($param['datetime']);

            if ($advanceTime === false)
            {
                return show(config('code.error'), '时间格式异常');
            }

            [$year, $month, $day, $hour, $minute, $is_summer] = explode(',', date('Y,m,d,H,i,I', $advanceTime));

//            list($year, $month, $day, $hour, $minute, $is_summer) = explode(',', date('Y,m,d,H,i,I', $advanceTime));

            $advanceInfo = [
                'year' => $year * 1,
                'month' => $month * 1,
                'day' => $day * 1,
                'hour' => $hour * 1,
                'minute' => $minute * 1,
                'timezone' => $param['timezone'] * 1,
                'is_summer' => $is_summer * 1,
            ];
            if (isset($param['longitude']))
            {
                $advanceInfo['longitude'] = $param['longitude'];
            }
            if (isset($param['latitude']))
            {
                $advanceInfo['latitude'] = $param['latitude'];
            }
            $Astrolog->setAdvance($advanceInfo);
        }

        $userSetting = [$param['chart'] => $settingData];

        // 法达参数数字转为字符串
        if (isset($userSetting[$param['chart']]['firdaria']))
        {
            if ($userSetting[$param['chart']]['firdaria'] === 0)
            {
                $userSetting[$param['chart']]['firdaria'] = 'default';
            } else
            {
                $userSetting[$param['chart']]['firdaria'] = 'another';
            }
        }

        // 界主星参数数字转为字符串
        if (isset($userSetting[$param['chart']]['bound_type']))
        {
            if ($userSetting[$param['chart']]['bound_type'] === 0)
            {
                $userSetting[$param['chart']]['bound_type'] = 'default';
            } else
            {
                $userSetting[$param['chart']]['bound_type'] = 'ptolemy_world';
            }
        }

        // v2.9.8支持调起标记盘，需要返回标记数据
        if ($param['chart'] === 'natal' && isset($param['basis']) && $param['basis'] !== '')
        {
            // 标记盘需要固定设置，此处特殊处理
            $userSetting['natal'] = json_decode('{"planet":[[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[1,0],[0,0],[0,0],[1,0]],"phase":{"0":[1,8],"60":[1,6],"90":[1,7],"120":[1,7],"180":[1,7],"45":[0,0],"135":[0,0],"30":[0,0],"150":[0,0],"72":[0,0],"144":[0,0]},"arabic":[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],"h_sys":"p","ecliptic":0,"firdaria":"default","profection_push_direction":0,"decanates":0,"bound_type":"default","ayanamsa":0}', true);
        }

        $data = $Astrolog->setExecPrefix(config('astrolog.prefix'))
            ->setIsAstrolabe(true)
            ->setUserSetting($userSetting)
            ->setVersion(2)
            ->setGetDatas([$param['chart']])
            ->getAstroDatas()
            ->getDatas($param['chart']);

        $error = $Astrolog->getError();

        if ($error)
        {
            Log::write('index:' . $error);

            return show(config('code.error'), $error);
        }

        if (in_array($param['chart'], ['now', 'natal', 'profection', 'firdaria', 'dodekatemorion', 'trimsamsa', 'zodrel', 'fortune']))
        {
            $data['extent_type'] = $settingData['bound_type'] ?? 0;
        }
        //  获取系统配置
        if ($param['chart'] === 'natal')
        {
            // $astro_config = config('astro');
            // $data['icon_info'] = [
            //     'horoscope_name' => $astro_config['horoscope_name'],
            //     'divination_name' => $astro_config['divination_name'],
            //     'divination_target' => 'local',
            //     'divination_link' => $this->user['young_model'] ? 'divination_question?type=0&name1=占星骰子&name2=塔罗占卜&need_auth=3' : 'divination_question?type=0&name1=占星骰子&name2=塔罗占卜&need_auth=0',
            //     'status' => $astro_config['status'],
            // ];
            // $data['natal_report_name'] = '一生报告';
            $oss = Env::get('host.photo');
            if (Util::AppIsPassShowV1())
            {
                $data['btn_list'] = [
                    [
                        'name' => '星座解读',
                        'icon' => $oss . '/test/jd.png',
                        'target' => 'link',
                        'link' => Env::get('host.domain') . '/web/astro_explain_new/index.html?rid=' . $param['id'] . '&need_auth=1',
                    ],
                    [
                        'name' => '提问解惑',
                        'icon' => $oss . '/test/tw.png',
                        'target' => 'local',
                        'link' => 'divination_question?type=0&name1=%E5%8D%A0%E6%98%9F%E9%AA%B0%E5%AD%90&name2=%E5%A1%94%E7%BD%97%E5%8D%A0%E5%8D%9C&need_auth=3',
                    ],
                ];
            } else
            {
                if ($this->user['young_model'])
                {
                    $data['btn_list'] = [
                        [
                            'name' => Util::CheckAppVersion('2.10.0') !== '小' ? '深度解读' : '一生报告',// 一生预测
                            'icon' => $oss . '/test/yc.png',
                            'target' => 'local',
                            'link' => 'report_index?rid=' . $param['id'] . '&need_auth=3',
                        ],
                        [
                            'name' => '星座解读',
                            'icon' => $oss . '/test/jd.png',
                            'target' => 'local',
                            'link' => "horoscope_analysis_info?tab_index=0&rid={$param['id']}&need_auth=3",
                        ],
                        [
                            'name' => '提问解惑',
                            'icon' => $oss . '/test/tw.png',
                            'target' => 'local',
                            'link' => 'divination_question?type=0&name1=%E5%8D%A0%E6%98%9F%E9%AA%B0%E5%AD%90&name2=%E5%A1%94%E7%BD%97%E5%8D%A0%E5%8D%9C&need_auth=3',
                        ],
                    ];
                } else
                {
                    if (Util::CheckAppVersion('2.10.0') !== '小')
                    {
                        $n = '深度解读';
                    } else
                    {
                        $n = Util::IsHuawei() && Util::CheckAppVersion('2.9.10') === '大' ? '报告' : '一生报告';
                    }
                    $data['btn_list'] = [
                        [
                            'name' => $n,// 一生预测
                            'icon' => $oss . '/test/yc.png',
                            'target' => 'local',
                            'link' => 'report_index?rid=' . $param['id'] . '&need_auth=1',
                        ],
                        [
                            'name' => '星座解读',
                            'icon' => $oss . '/test/jd.png',
                            'target' => 'local',
                            'link' => "horoscope_analysis_info?tab_index=0&rid={$param['id']}&need_auth=1",
                        ],
                        [
                            'name' => '提问解惑',
                            'icon' => $oss . '/test/tw.png',
                            'target' => 'local',
                            'link' => 'divination_question?type=0&name1=%E5%8D%A0%E6%98%9F%E9%AA%B0%E5%AD%90&name2=%E5%A1%94%E7%BD%97%E5%8D%A0%E5%8D%9C&need_auth=0',
                        ],
                    ];
                }
                if (Util::CheckAppVersion('2.9.6') === '小')
                {   // 旧版本
                    $data['btn_list'][] = [
                        'name' => '八字',// 八字排盘
                        'icon' => $oss . '/test/bz.png',
                        'target' => 'local',
                        'link' => 'horoscope?rid=' . $param['id'] . '&need_auth=1',
                    ];
                    $data['btn_list'][1]['target'] = 'link';
                    $data['btn_list'][1]['link'] = Env::get('host.domain') . '/web/astro_explain_new/index.html?rid=' . $param['id'] . '&need_auth=1';
                }
            }
            // 查询问题列表 TODO 缓存
            $ExplainTitleList = (new Zl5ExplainTitle())->where('status', 1)->order('sort desc')->limit(10)->column('title');
            // 本命盘添加问题list
            $data['question_info'] = [
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/natal_chat/index?zhunle_not_show_nav=1&zhunle_nav_text_color=1&rid=' . (int)$param['id'] . '&need_auth=1',
                'list' => $ExplainTitleList,
            ];
            if (isset($param['basis']) && $param['basis'] !== '')
            {
                $data['tagged_element_list'] = [
                    'p_list' => [],// 行星ID列表
                    's_list' => [],// 星座ID列表
                    'h_list' => [],// 宫位ID列表
                    'fs_list' => [],// 恒星索引列表
                    'ps_list' => [],// 宫主星 所在星座ID列表
                ];
                $basisArr1 = explode(':', $param['basis']);
                $basisType = (int)$basisArr1[0];
                $basisArr2 = explode('-', $basisArr1[1]);
                switch ($basisType)
                {
                    case 1:
                        // 行星落座（行星、星座）
                        $data['tagged_element_list']['p_list'][] = (int)$basisArr2[0];
                        $data['tagged_element_list']['s_list'][] = (int)$basisArr2[1];
                        break;
                    case 2:
                        // 行星落宫（行星、宫位）
                        $data['tagged_element_list']['p_list'][] = (int)$basisArr2[0];
                        $data['tagged_element_list']['h_list'][] = (int)$basisArr2[1];
                        break;
                    case 3:
                        // 宫主星飞宫（宫主星、行星、宫位）
                        $data['tagged_element_list']['ps_list'][] = $data['houses'][$basisArr2[0]]['in_sign_id'];
                        $data['tagged_element_list']['p_list'][] = $data['houses'][$basisArr2[0]]['protect_id'];
                        $data['tagged_element_list']['h_list'][] = $data['houses'][$basisArr2[0]]['protect_inhouse_id'];
                        break;
                    case 4:
                        // 宫头星座（宫位、星座）
                        $data['tagged_element_list']['h_list'][] = (int)$basisArr2[0];
                        $data['tagged_element_list']['s_list'][] = (int)$basisArr2[1];
                        break;
                }
            }
        } elseif ($param['chart'] === 'synastry')
        {   // 合盘
            if (Util::checkAppVersion('2.13.0') !== '小')
            {
                $link = "synastry_result?type=7&rid1={$param['id1']}&rid2={$param['id2']}&synastry_type=7&need_auth=1";
            } else
            {
                $link = "synastry_result?type=2&rid1={$param['id1']}&rid2={$param['id2']}&need_auth=1";
            }
            $btnList = [
                [
                    'name' => Util::IsHuawei() && Util::CheckAppVersion('2.10.0') !== '小' ? '关系解析' : '合盘解读',
                    'target' => 'local',
                    'link' => $link,
                ],
            ];
            // 获取 合盘报告 显隐开关 true=>显示 false=>隐藏
            $synastryReportSwitch = Util::getSynastryReportSwitch();
            if ($synastryReportSwitch && Util::CheckAppVersion('2.5.2') !== '小' && !Util::AppIsPassShowV1()) // 非合规情况显示
            {
                // 获取 当前合盘星盘两个档案是否已经解锁过相关关系
                $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($this->user['id'], (int)$param['id1'], (int)$param['id2'], 1);

                $synastryReportNeedAuth = $this->user['young_model'] ? 3 : 1;
                $btnList[] = [
                    'name' => '合盘报告',
                    'target' => 'local',
                    'link' => $unlockStatus ? "synastry_report_list?rid1={$param['id1']}&rid2={$param['id2']}&srid=1&need_auth={$synastryReportNeedAuth}" : "synastry_report_detail?rid1={$param['id1']}&rid2={$param['id2']}&srid=1&need_auth={$synastryReportNeedAuth}",
                ];
            }

            $data = [
                'astro_list' => $data,
                'btn_list' => $btnList,
            ];
        }


        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 验证客户端传递的参数是否正确
     * @param array $param
     * @return bool|string
     */
    private function checkParam($param = [])
    {
        if (!isset($param['chart']) || !in_array($param['chart'], config('astroset175.chart'), true))
        {
            return '未知星盘';
        }
        // 带档案id的盘
        $single = ['natal', 'transits', 'thirdprogressed', 'thirdprogressedvsnatal', 'progressions', 'progressionsvsnatal', 'solar', 'solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal', 'firdaria', 'profection', 'fortune', 'zodrel', 'dodekatemorion', 'trimsamsa'];
        // 档案id1 和 档案id2 的盘
        $double = ['composite_thirdprogressed', 'synastry', 'composite_progressions', 'composite', 'davison', 'marks', 'synastry_thirdprogressed', 'synastry_progressions', 'davison_thirdprogressed', 'davison_progressions', 'marks_thirdprogressed', 'marks_progressions',];
        // 带推运时间 datetime 和 时区timezone 的盘
        $advance = ['now', 'transits', 'thirdprogressed', 'thirdprogressedvsnatal', 'progressions', 'progressionsvsnatal', 'solar', 'solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal', 'firdaria', 'profection', 'composite_thirdprogressed', 'composite_progressions', 'synastry_thirdprogressed', 'synastry_progressions', 'davison_thirdprogressed', 'davison_progressions', 'marks_thirdprogressed', 'marks_progressions',];

        $divination = ['divination'];

        // 天象盘验证
        if ($param['chart'] === 'now' && (!isset($param['longitude'], $param['latitude'])))
        {
            return '参数错误';
        }
        // 单盘验证
        if (in_array($param['chart'], $single, true))
        {
            if (!isset($param['id']) || $param['id'] <= 0)
            {
                return '档案错误';
            }
        }
        // 双盘验证
        if (in_array($param['chart'], $double, true))
        {
            if (!isset($param['id1'], $param['id2']) || $param['id1'] <= 0 || $param['id2'] <= 0)
            {
                return '档案错误';
            }
        }
        // 推进盘验证
        if (in_array($param['chart'], $advance, true))
        {
            if (!isset($param['datetime']) || strtotime($param['datetime']) === false)
            {
                return '时间错误';
            }

            if (!isset($param['timezone']) || $param['timezone'] > 12 || $param['timezone'] < -12)
            {
                return '时区错误';
            }
        }
        // 卜卦盘验证
        if (in_array($param['chart'], $divination, true))
        {
            if (!isset($param['did']) || $param['did'] <= 0)
            {
                return '未找到该卜卦';
            }
        }

        return true;
    }
}
